package com.cookbook.cookbookservice.common.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @program: tourism-admin-service
 * @ClassName FileUtil
 * @description:
 * @author: MiaoChao
 * @create: 2024-02-29 16:08
 * @Version 1.0
 **/
@Slf4j
public class FileUtil {


    public static String saveFile(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String fileExtensionName = fileName.substring(fileName.lastIndexOf("."));
        String newFileName = System.currentTimeMillis() + fileExtensionName;
        String path = System.getProperty("user.dir") + "/static/img/";
        if (!new File(path).exists()) {
            new File(path).mkdirs();
        }
        try {
            file.transferTo(new File(path + newFileName));
            return newFileName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String saveFileInHtml(String htmlText) {
        try {
            Pattern pattern = Pattern.compile("<img[^>]+src=\"([^\"]+)\"");
            Matcher matcher = pattern.matcher(htmlText);
            InetAddress localHost = null;
            localHost = InetAddress.getLocalHost();
            // 输出解析出的图片地址
            while (matcher.find()) {
                String imageUrl = matcher.group(1);
                String s = saveFile(imageUrl, imageUrl.substring(imageUrl.lastIndexOf("/")));
                htmlText = htmlText.replace(imageUrl, localHost + "/img/" + s);
            }
        } catch (Exception e) {
            log.info("解析html中的图片地址报错 {}", e);
        }
        return htmlText;
    }

    public static String saveFile(String imgUrl, String newName) {
        try {
            log.info("imgUrl:{}, newName:{}", imgUrl, newName);
            URL url = new URL(imgUrl);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());
            String newFileName = newName + ".jpg";
            File file = new File(System.getProperty("user.dir") + "/static/img/" + newFileName);
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int length;
            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
            return file.getAbsolutePath();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

//    public static String uploadCOS(String localFilePath) {
//        // 1 初始化用户身份信息（secretId, secretKey）。
//        // SECRETID 和 SECRETKEY 请登录访问管理控制台 https://console.cloud.tencent.com/cam/capi 进行查看和管理
//        String secretId = "AKIDw479A2udEhCYtpvtiNrB8rHJzt0vx6Lg";//用户的 SecretId，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
//        String secretKey = "XCvCbnjs2mihuP75mbYuY2kYdBlYQ4xR";//用户的 SecretKey，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
//        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
//        // 2 设置 bucket 的地域, COS 地域的简称请参见 https://cloud.tencent.com/document/product/436/6224
//        // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
//        Region region = new Region("ap-nanjing");
//        ClientConfig clientConfig = new ClientConfig(region);
//// 这里建议设置使用 https 协议
//// 从 5.6.54 版本开始，默认使用了 https
//        clientConfig.setHttpProtocol(HttpProtocol.https);
//// 3 生成 cos 客户端。
//        COSClient cosClient = new COSClient(cred, clientConfig);
////        上传图片
//        File localFile = new File(localFilePath);
//        // 指定文件将要存放的存储桶
//        String bucketName = "suixinyou-1309452461";
//        // 指定文件上传到 COS 上的路径，即对象键。例如对象键为 folder/picture.jpg，则表示将文件 picture.jpg 上传到 folder 路径下
//        String key = "scenicbgp/test.jpg";
//        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
//        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
//        System.out.println(JSON.toJSONString(putObjectResult));
//        return key;
//    }

    public static String deleteFile(String filePath) {
        Path path = Paths.get(filePath);
        try {
            Files.delete(path);
            return "删除成功";
        } catch (IOException e) {
            log.info("删除失败 {}", e);
            return "删除失败";
        }
    }

}